package wechatpay

import (
	"context"
	"crypto/rsa"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"log"
	"pay/config"
)

type WechatPayConfig struct {
}

type Client struct {
	WechatClient  *core.Client
	Ctx           context.Context
	AppId         string
	MchID         string
	MchPrivateKey *rsa.PrivateKey
}

var MyClient Client

func (wechatPay WechatPayConfig) Init() {
	fmt.Println(111)
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath(config.Config.Wechat.Path)
	if err != nil {
		log.Print("load merchant private key error")
	}
	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(config.Config.Wechat.MchId, config.Config.Wechat.MchCertificateSerialNumber, mchPrivateKey, config.Config.Wechat.MchAPIv3Key),
	}
	fmt.Println(config.Config.Wechat.MchId, config.Config.Wechat.MchCertificateSerialNumber, mchPrivateKey, config.Config.Wechat.MchAPIv3Key)
	MyClient.Ctx = ctx
	MyClient.MchPrivateKey = mchPrivateKey
	MyClient.AppId = config.Config.Wechat.AppId
	MyClient.MchID = config.Config.Wechat.MchId
	MyClient.WechatClient, err = core.NewClient(MyClient.Ctx, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err)
		panic("微信支付初始化错误")
	}
}
